package com.xhj.bigfactory.bigFactory.volatile0;

import java.util.concurrent.atomic.AtomicInteger;

import static java.lang.System.out;
import static java.lang.Thread.currentThread;
/**
 * -
 *
 * @author 周沫 @Date 2021-07-20 @Time 9:44
 */
public class Atomic {

  public static void main(String[] args) {
    MyData3 myData = new MyData3();
    for (int i = 0; i < 20; i++) {
      new Thread(
              () -> {
                for (int j = 0; j < 1000; j++) {
                  myData.addPlusPlus();
                }
              },
              "thread" + i)
          .start();
    }
    while (Thread.activeCount() > 2) {}
    out.println("myData.number = " + myData.number);
    new Thread(
            () -> {
              out.println(currentThread().getName() + " come in...");
              myData.addPlusPlus();
              myData.decPlusPlus();
            },
            "AAA")
        .start();
  }
}

class MyData {

  int number = 0; // - - - - - 多线程不可见

  public void addPlusPlus() {
    number++;
  }
}

class MyData2 {

  volatile int number = 0; // - - - - - 不保证原子性

  public synchronized void addPlusPlus() {
    number++;
  }
}

class MyData3 {

  AtomicInteger number = new AtomicInteger(0); // - - - - - 原子性

  public void addPlusPlus() {
    //    number.getAndAdd(1);
    number.getAndIncrement();
  }

  public void decPlusPlus() {
    //    number.getAndAdd(1);
    number.getAndDecrement();
  }
}
